package com.yunfei.api.v2.service;
import com.google.gson.Gson;
import com.yunfei.api.v1.magerIndcInfo.service.MagerIndcInfoService;
import com.yunfei.api.v2.common.YunHeTongApiContant;
import com.yunfei.api.v2.contants.TemplateReplaceKeyValueList;
import com.yunfei.api.v2.elecHeTong.json.ContractData;
import com.yunfei.api.v2.elecHeTong.json.ContractTable;
import com.yunfei.api.v2.elecHeTong.json.ContractTables;
import com.yunfei.api.v2.elecHeTong.json.CreateElecHtJsonRootBean;
import com.yunfei.api.v2.enums.CancelElecHtEnum;
import com.yunfei.api.v2.enums.GetAccountInfoEnum;
import com.yunfei.api.v2.param.ContractIdParam;
import com.yunfei.api.v2.param.CustNoParam;
import com.yunfei.api.v2.param.ProjIdParam;
import com.yunfei.api.v2.param.ReserveNoParam;
import com.yunfei.api.v2.result.YuYueInfoResult;
import com.yunfei.api.v2.result.createTemplate.CreateTemplateJsonRootBean;
import com.yunfei.api.v2.result.createTemplate.Data;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.enums.ResultStatus;
import com.yunfei.mapper.aiiidb.AccountInfoMapper;
import com.yunfei.mapper.aiiidb.ElecContBeneAcceMapper;
import com.yunfei.mapper.aiiidb.HeTongSignInfoMapper;
import com.yunfei.procedure.GetContractNoProcedure;
import com.yunfei.procedure.ProcedureResultModel;
import com.yunfei.utils.http.CreateTemplateHttpUtil;
import com.yunfei.utils.jdbc.AiiidbUtil;
import com.yunfei.utils.string.StringUtil;
import com.yunfei.yunhetong.magerIndeInfo.entity.MagerIndcInfoEntity;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CreateElecHtService {
    @Autowired
    private HeTongSignInfoMapper heTongSignInfoMapper;
    @Autowired
    private MagerIndcInfoService magerIndcInfoService;
    @Autowired
    private HTYuYueInfoService htYuYueInfoService;
    @Autowired
    private AccountInfoMapper getAccountInfoMapper;
    @Autowired
    private ElecContBeneAcceMapper elecContBeneAcceMapper;
    @Autowired
    private AddSignerService addSignerService;
    @Autowired
    private Environment env;
    /**
    * @Description: 生成电子合同
    * @Author: zhengyunfei
    * @Date: 2019/8/15
    * @time:9:33
    */
    public Object create(String token, ReserveNoParam param, ProjIdParam projIdParam, CustNoParam custNoParam){
        ResultModel resultModel=new ResultModel();
        YuYueInfoResult yueInfoResult=null;
        String reserveNo=param.getReserveNo();//预约编号
        String projId=projIdParam.getProjId();//营销项目编号
        String custNo=custNoParam.getcCustNo();//客户号
        String contractNum="";//合同编号
        CreateElecHtJsonRootBean createElecHtJsonRootBean=new CreateElecHtJsonRootBean();
        GetContractNoProcedure getContractNoProcedure=new GetContractNoProcedure();
        //获取数据库连接
        AiiidbUtil aiiidbUtil=AiiidbUtil.getInstance(env);
        ProcedureResultModel procedureResultModel=getContractNoProcedure.callProcedure(aiiidbUtil,projId);
        String contNo=procedureResultModel.getReturnCode();
        if(StringUtil.isNullOrEmpty(procedureResultModel)){
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(procedureResultModel.getReturnInfo());
            return resultModel;
        }
        //根据预约编号获取预约信息
        resultModel= htYuYueInfoService.get(param);
        Object object=resultModel.getData();
        Map<String,Object> projIdMap=new HashMap<>();
        if(!StringUtil.isNullOrEmpty(object)){
            projIdMap.put("projId",projId);
            List<ContractTable> tableResult=htYuYueInfoService.getTableList(projIdMap);
            yueInfoResult= (YuYueInfoResult) resultModel.getData();//预约信息（获取电子合同要素
            yueInfoResult.setContNo(contNo);
            String mandatorId=yueInfoResult.getMandatorId();//管理人id
            contractNum=yueInfoResult.getContNo();//合同编号
            //根据管理人ID查询模板
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("crmMagerId",mandatorId);
            MagerIndcInfoEntity magerIndcInfoEntity= magerIndcInfoService.findByMap(queryMap);//合同信息
            createElecHtJsonRootBean.setContractNo(yueInfoResult.getContNo());
            createElecHtJsonRootBean.setContractTitle(yueInfoResult.getContNo());
            createElecHtJsonRootBean.setTemplateId(magerIndcInfoEntity.getContractId());
            ContractData contractData= ContractData.getContractData(yueInfoResult);
            ContractTables contractTables=new ContractTables();
            contractTables.setIndex(0);
            contractTables.setTable(tableResult);
            List<ContractTables> contractTablesList=new ArrayList<>();
            contractTablesList.add(contractTables);
            contractData.setTables(contractTablesList);
            createElecHtJsonRootBean.setContractData(contractData);
            resultModel.setData(createElecHtJsonRootBean);
        }else{
            resultModel.setMessage("此预约编号没有对应的预约信息,请核对");
            return resultModel;
        }
        //替换为模板需要的json数据格式
        Gson gson=new Gson();
        StringBuffer result=TemplateReplaceKeyValueList.replace(gson.toJson(createElecHtJsonRootBean));
        //调用云合同生成电子合同的接口
        System.out.println("参数====="+result.toString());
        System.out.println("token====="+token);
        String url= YunHeTongApiContant.CREATE_ELEC_CONTRACT_API;
        JSONObject resultJsonObject= CreateTemplateHttpUtil.post(token,url,result.toString());
        CreateTemplateJsonRootBean createTemplateJsonRootBean= (CreateTemplateJsonRootBean) JSONObject.toBean(resultJsonObject, CreateTemplateJsonRootBean.class);
       int code=createTemplateJsonRootBean.getCode();
       if(code==200){
           long contractId=createTemplateJsonRootBean.getData().getContractId();
           System.out.println("contractId======================="+contractId);
           //更新电子合同
           Map<String,Object> updateParam=new HashMap<>();
           updateParam.put("contractId",contractId);
           updateParam.put("contractNum",contractNum);
           updateParam.put("reserveNo",reserveNo);
           elecContBeneAcceMapper.update(updateParam);
           //添加签署者
           resultModel=addSignerService.addSigner(contractId+"",custNo,projId);
           resultModel.setCode(ResultStatus.SUCCESS.getCode());
           resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
           return createTemplateJsonRootBean;
       }else{
           String msg=createTemplateJsonRootBean.getMsg();
           resultModel.setCode(code);
           resultModel.setMessage(msg);
           Data data=createTemplateJsonRootBean.getData();
           resultModel.setData(data);
           return resultModel;
       }
    }

    /**
     * @Description: 生成作废协议
     * @Author: zhengyunfei
     * @Date: 2019/8/15
     * @time:9:33
     */
    public Object createZuoFeiXieYi(String token, ReserveNoParam param, ProjIdParam projIdParam, CustNoParam custNoParam){
        ResultModel resultModel=new ResultModel();
        YuYueInfoResult yueInfoResult=null;
        String reserveNo=param.getReserveNo();//预约编号
        String projId=projIdParam.getProjId();//营销项目编号
        String custNo=custNoParam.getcCustNo();//客户号
        CreateElecHtJsonRootBean createElecHtJsonRootBean=new CreateElecHtJsonRootBean();
        //根据预约编号获取预约信息
        resultModel= htYuYueInfoService.get(param);
        Object object=resultModel.getData();
        Map<String,Object> projIdMap=new HashMap<>();
        if(!StringUtil.isNullOrEmpty(object)){
            projIdMap.put("projId",projId);
            List<ContractTable> tableResult=htYuYueInfoService.getTableList(projIdMap);
            yueInfoResult= (YuYueInfoResult) resultModel.getData();//预约信息（获取电子合同要素
            String mandatorId=yueInfoResult.getMandatorId();//管理人id
            //根据管理人ID查询模板
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("crmMagerId",mandatorId);
            MagerIndcInfoEntity magerIndcInfoEntity= magerIndcInfoService.findByMap(queryMap);//合同信息
            createElecHtJsonRootBean.setContractNo(yueInfoResult.getContNo());
            createElecHtJsonRootBean.setContractTitle(yueInfoResult.getContNo());
            createElecHtJsonRootBean.setTemplateId(magerIndcInfoEntity.getContractId());
            ContractData contractData= ContractData.getContractData(yueInfoResult);
            ContractTables contractTables=new ContractTables();
            contractTables.setIndex(0);
            contractTables.setTable(tableResult);
            List<ContractTables> contractTablesList=new ArrayList<>();
            contractTablesList.add(contractTables);
            contractData.setTables(contractTablesList);
            createElecHtJsonRootBean.setContractData(contractData);
            resultModel.setData(createElecHtJsonRootBean);
        }else{
            resultModel.setMessage("此预约编号没有对应的预约信息,请核对");
            return resultModel;
        }
        //替换为模板需要的json数据格式
        Gson gson=new Gson();
        StringBuffer result=TemplateReplaceKeyValueList.replace(gson.toJson(createElecHtJsonRootBean));
        //调用云合同生成电子合同的接口
        System.out.println("参数====="+result.toString());
        System.out.println("token====="+token);
        String url= YunHeTongApiContant.CREATE_ELEC_CONTRACT_API;
        JSONObject resultJsonObject= CreateTemplateHttpUtil.post(token,url,result.toString());
        CreateTemplateJsonRootBean createTemplateJsonRootBean= (CreateTemplateJsonRootBean) JSONObject.toBean(resultJsonObject, CreateTemplateJsonRootBean.class);
        int code=createTemplateJsonRootBean.getCode();
        if(code==200){
            long contractId=createTemplateJsonRootBean.getData().getContractId();
            String contractNum=heTongSignInfoMapper.getEhtNo(projIdMap);
            System.out.println("contractId======================="+contractId);
            //更新电子合同
            Map<String,Object> updateParam=new HashMap<>();
            updateParam.put("contractId",contractId);
            updateParam.put("contractNum",contractNum);
            updateParam.put("reserveNo",reserveNo);
            elecContBeneAcceMapper.update(updateParam);
            //添加签署者
            resultModel=addSignerService.addSigner(contractId+"",custNo,projId);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            return createTemplateJsonRootBean;
        }else{
            String msg=createTemplateJsonRootBean.getMsg();
            resultModel.setCode(code);
            resultModel.setMessage(msg);
            Data data=createTemplateJsonRootBean.getData();
            resultModel.setData(data);
            return resultModel;
        }
    }


    /**
   * @Description: 作废电子合同
   * @Param: contractId 云合同对应的id
   * @Author: zhengyunfei
   * @Date: 2019/8/15
   * @time:9:33
   */
    public Object cancel(ReserveNoParam param){
            ResultModel resultModel=new ResultModel();
            String reserveNo=param.getReserveNo();//云合同对应的id
            if(StringUtil.isNullOrEmpty(reserveNo)){
                resultModel.setCode(GetAccountInfoEnum.RESERVENO_NOTNULL.getCode());
                resultModel.setMessage(GetAccountInfoEnum.RESERVENO_NOTNULL.getMessage());
                return resultModel;
            }
            try{
                //作废电子合同
                Map<String,Object> updateParam=new HashMap<>();
                updateParam.put("reserveNo",reserveNo);
                elecContBeneAcceMapper.zuoFei(updateParam);
                resultModel.setCode(ResultStatus.SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            }catch (Exception e){
                e.printStackTrace();
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage(ResultStatus.ERROR.getMessage());
            }
            return resultModel;

    }


}
